/**
 * Created by xiaopingfeng on 10/5/17.
 */
var logger = require('log4js').getLogger('raw');

var fs = require('fs')
var Faye = require('faye')
var client = new Faye.Client('http://localhost:8001/events')

var result_dir = 'data/result/'
function writeResultLog(session_id, type, data) {
  // console.log('result', data)
  data = JSON.parse(data)
  var node_id = undefined
  if ("rtkres_attitude" == type) {
    node_id = "global"
  } else {
    node_id = data.nodeID
  }
  console.log(type, JSON.stringify(data))
  fs.appendFileSync(
      result_dir + session_id + '_' + node_id + '.' + type,
      JSON.stringify(data) + '\n')
  return data
}

var EVENTS = [
  'status',
  'uwbbase_stat',
  'user_uwb',
  'user_stat',
  'rtkres_attitude',
  'rtkres_basepos',
  'rtkres_baseobs',
  'rtkres_roverpos',
  'rtkres_roverobs'
]

var express = require('express');
var socketio_server = require('http').createServer(express);
var io = require('socket.io')(socketio_server);
io.on('connection', (socket) => {
  var remoteAddress = socket.client.conn.remoteAddress,
      remotePort = socket.client.conn.remotePort

  var session_id = new Date().getTime()

  logger.info('connection', remoteAddress, remotePort)

  var listener = function onRaw(result) {
    // console.log('send', result.node_id)
    socket.emit('raw', result.raw_pkg)
    logger.info('frame_to_wrapper', result)
  }

  client.subscribe('/frames', listener);

  EVENTS.forEach(function (eventName) {
    socket.on(eventName, function (data) {
      data = writeResultLog(session_id, eventName, data)
      client.publish('/node', {
        name: eventName,
        data: data,
      })
      logger.info('result_event', eventName, data)
    })
  })

  socket.on('disconnect', function () {
    logger.info('disconnect', remoteAddress, remotePort)
    client.cancel()
  })
})

socketio_server.listen(3000, '0.0.0.0');